package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    CheckGroupDao checkGroupDao;
    @Override
    public void add(CheckGroup checkGroup, Integer[] checkItemIds) {
        checkGroupDao.addGroup(checkGroup);
        Integer checkGroupId=checkGroup.getId();
        setGroupAndItemMap(checkItemIds, checkGroupId);

    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<CheckGroup> page=checkGroupDao.findByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page);
    }

    @Override
    public void deleteById(int id) {
        checkGroupDao.deleteGroupAndItemByGroupId(id);
        checkGroupDao.deleteCheckGroupById(id);
    }

    @Override
    public CheckGroup findGroupById(int id) {
        CheckGroup checkGroup=checkGroupDao.findGroupById(id);
        List<CheckItem> checkItems=checkGroupDao.findItemsByGroupId(id);
        checkGroup.setCheckItems(checkItems);
        return checkGroup;
    }

    @Override
    public void update(CheckGroup checkGroup, Integer... checkItemIds) {
        checkGroupDao.updateGroup(checkGroup);
        checkGroupDao.deleteGroupAndItemByGroupId(checkGroup.getId());
        setGroupAndItemMap(checkItemIds, checkGroup.getId());
    }

    @Override
    public List<CheckGroup> findAllGroup() {
        return checkGroupDao.findAllGroup();
    }

    private void setGroupAndItemMap(Integer[] checkItemIds, Integer checkGroupId) {
        HashMap<String, Integer> map = new HashMap<>();
        for (Integer checkItemId : checkItemIds) {
            map.put("checkGroupId",checkGroupId);
            map.put("checkItemId",checkItemId);
            checkGroupDao.addGroupAndItem(map);
        }
    }
}
